package com.hw.blog.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Session 처리하는 Filter 클래스.
 * 
 * @author Jeasu Kim
 * @version 1.0
 */
public class SessionCheckFilter implements Filter {

	/**
	 * 로그를 남기기 위한 셋팅
	 */
	private Logger logger = Logger.getLogger(getClass());

	/**
	 * 세션이 없을 경우 로그인 처리를 해줄 페이지 주소.
	 */
	public final static String loginUrl = "/login/login_form.aap";

	/**
	 * filter 셋팅을 위한 환경설정 객체.
	 */
	protected FilterConfig filterConfig = null;

	/**
	 * filter 서비스 사용을 위해 web container에 의해 호출된다.
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	/**
	 * filter 서비스 종료를 위해 web container에 의해 호출된다.
	 */
	public void destroy() {
		this.filterConfig = null;
	}

	/**
	 * 세션을 체크하는 filter를 실행시킨다.
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		String uriExcludingContextPath = requestURI.substring(contextPath
				.length());

		// System.out.println("uriExcludingContextPath = " +
		// uriExcludingContextPath);
		req.setAttribute("url", uriExcludingContextPath);

		HttpSession session = request.getSession();
		Map userInfo = (Map) session.getAttribute("userInfo");

		if (uriExcludingContextPath.startsWith("/common/")
				|| uriExcludingContextPath.startsWith("/test/")) {
			// common, images, itg-tag 폴더는 세션 처리 대상에서 제외된다.
			chain.doFilter(request, response);
		} else if (uriExcludingContextPath.equals("/json.aap")
				|| uriExcludingContextPath.equals("/json_aes.aap")
				|| uriExcludingContextPath.equals("/json.aap.aap")
				|| uriExcludingContextPath.equals("/reqVerify.html")
				|| uriExcludingContextPath.equals("/system/agentInsert.aap")) {
			// agent 요청
			rejectProtocolAccess(request, response, chain);
		} else {

			boolean hasSession = !(userInfo == null || userInfo.get("user_id")
					.equals(""));

			if (!hasSession) {

				if (uriExcludingContextPath.equals(loginUrl)) {
					RequestDispatcher dispatcher = filterConfig
							.getServletContext().getRequestDispatcher(loginUrl);
					dispatcher.forward(request, response);
				} else {
					response.sendRedirect(contextPath + loginUrl);
				}

			} else if (uriExcludingContextPath.equals("/")) {
				RequestDispatcher dispatcher = filterConfig.getServletContext()
						.getRequestDispatcher("/dashboard/dashboard.aap");
				dispatcher.forward(request, response);
			} else {
				// 세션이 있으면 해당 페이지 접근을 허용한다.

				chain.doFilter(request, response);
			}
		}
	}

	/**
	 * 통신 Protocol 접근 권한이 없을 때 보여질 XML을 생성한다.
	 * 
	 * @param request
	 *            servlet에 요구할 클라이언트의 request를 포함하는 {@link HttpServletRequest}
	 *            객체
	 * @param response
	 *            servlet에서 클라이언트로 return할 response를 포함하는
	 *            {@link HttpServletResponse} 객체
	 * @throws IOException
	 *             XML을 출력할 수 없을 때
	 * @throws ServletException
	 */
	private void rejectProtocolAccess(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		chain.doFilter(request, response);
	}
}
